import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  DatePicker,
  Modal,
  message,
  List,
  Avatar,
  Table,
  Tag,
  Popconfirm
} from 'antd';
import InputNumberRange from '@/components/InputNumberRange';
import moment from 'moment';
import styles from './index.less';

const {  RangePicker } = DatePicker;
const FormItem = Form.Item;
const { Option } = Select;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleAdd, handleModalVisible ,contentType} = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleAdd(fieldsValue);
    });
  };
  return (
    <Modal
      destroyOnClose
      title={contentType==1?'选择标签':contentType==2?'修改积分':contentType==3?'发会员卡':''}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="描述">
        {form.getFieldDecorator('desc', {
          rules: [{ required: true, message: '请输入至少五个字符的规则描述！', min: 5 }],
        })(<Input placeholder="请输入" />)}
      </FormItem>
    </Modal>
  );
});

/* eslint react/no-multi-comp:0 */
@connect(({global, customerList, loading }) => ({
    customerList:customerList.customerListInfo.customerList,
    customerListInfo:customerList.customerListInfo,
    allTagList:customerList.allTagList,
    cardList:customerList.cardList,
    oemInfo: global.oemInfo,
    loading: loading.effects['customerList/SearchMemberList'],
}))
@Form.create()
class TableList extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    expandForm: false,
    selectedRowKeys: [],
    formValues: {},
    paginationProps: {
      showSizeChanger: true,
      showQuickJumper: false,
      showTotal: total => `共 ${total} 条记录`,
      pageSize: 10,
      total: 0,
    },
    cardLoading:true
  };

  componentWillMount() {
    window.Isoption = false;
  }

  componentDidMount() {
    window.Isoption = true;
      //console.log(this.props)
    const { match } = this.props;
    this.requestList({CardIds:[match.params.id/1]});
    this.requestAllTagList();
    this.requestCardList();
  }

  requestList = (params) => {
    const { dispatch } = this.props;
    const { selectedRowKeys } = this.state;
    dispatch({
      type: 'customerList/SearchMemberList',
      payload:{
        PageIndex:params&&params.current?params.current:1,
        PageSize:params&&params.pageSize?params.pageSize:10,
        KeyWord:params&&params.KeyWord?params.KeyWord:'',
        MemberType:params&&params.MemberType?params.MemberType:"",
        CardIds:params&&params.CardIds?params.CardIds:[],
        MinLastBuyDate:params&&params.MinLastBuyDate?params.MinLastBuyDate:'',
        MaxLastBuyDate:params&&params.MaxLastBuyDate?params.MaxLastBuyDate:'',
        TagIds:params&&params.TagIds?params.TagIds:[],
        MinPoints:params&&params.MinPoints?params.MinPoints:"",
        MaxPoints:params&&params.MaxPoints?params.MaxPoints:"",
        MinCreateDate:params&&params.MinCreateDate?params.MinCreateDate:'',
        MaxCreateDate:params&&params.MaxCreateDate?params.MaxCreateDate:'',
        SortName:params&&params.SortName?params.SortName:'Id',
        Sort:params&&params.Sort?params.Sort:'Asc'
      },
      callback: {
        success: res => {
            if(res.Code ===0) {
                this.setState({
                  cardLoading: false,
                  selectedRowKeys:[]
                })
            }
        },
        error: res => {
          this.setState({
            cardLoading: false,
            selectedRowKeys:[]
          })
        }
      }
    });
  }

  requestTagList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'customerList/FindTagList',
    });
  }

  requestAllTagList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'customerList/FindAllTagList',
    });
  }

  requestCardList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'customerList/FindCardList',
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      current: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.SortName = `${sorter.field}`;
      params.Sort = `${sorter.order==="ascend"?"Asc":"Desc"}`;
    }else{
      params.SortName = `Id`;
      params.Sort = `Asc`;
    }

    console.log(params)
    this.requestList(params)
    // dispatch({
    //   type: 'rule/fetch',
    //   payload: params,
    // });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    this.requestList();
  };

  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        MinLastBuyDate: fieldsValue.LastBuyDate&&fieldsValue.LastBuyDate[0]? moment(fieldsValue.LastBuyDate[0]).format('YYYY-MM-DD'):'' ,
        MaxLastBuyDate: fieldsValue.LastBuyDate&&fieldsValue.LastBuyDate[1]? moment(fieldsValue.LastBuyDate[1]).format('YYYY-MM-DD'):'' ,
        MinCreateDate: fieldsValue.CreateDate&&fieldsValue.CreateDate[0]? moment(fieldsValue.CreateDate[0]).format('YYYY-MM-DD'):'' ,
        MaxCreateDate: fieldsValue.CreateDate&&fieldsValue.CreateDate[1]? moment(fieldsValue.CreateDate[1]).format('YYYY-MM-DD'):'' ,
        MinPoints: fieldsValue.Points&&fieldsValue.Points[0]? fieldsValue.Points[0]:'' ,
        MaxPoints: fieldsValue.Points&&fieldsValue.Points[1]? fieldsValue.Points[1]:'' ,
      };

      this.setState({
        formValues: values,
      });
      console.log(values)
      this.requestList({...values})
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleAdd = type => {
    const { selectedRowKeys } = this.state;
    if(!selectedRowKeys.length) return message.error('至少选择一位会员');
    this.setState({contentType:type},()=>{
      this.handleModalVisible(true);
    });
  };

  deleteTag = (MemberId,TagId) => {
    const { dispatch ,customerListInfo:{customerList}} = this.props;
    dispatch({
      type: 'customerList/DelMemberTag',
      payload:{
        MemberId,
        TagId,
      } ,
      callback:{
        success:(res)=>{
          if(res.Code==0){
            let index=customerList.findIndex((item)=>item.Id===MemberId);
            customerList.splice(index,1);
            message.success('已删除');
            dispatch({
              type:'customerList/changeCustomerList',
              payload:customerList
            })
            //this.requestList();
          }
        }
      }
    });
  }

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 8 },
    };
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="关键词"  {...formItemLayout}>
              {getFieldDecorator('KeyWord')(<Input placeholder="请输入" className="xkd-width-per-100"/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="客户身份" {...formItemLayout}>
              {getFieldDecorator('MemberType')(
                <Select placeholder="请选择" className="xkd-width-per-100">
                  <Option value={0}>全部</Option>
                  <Option value={1}>客户</Option>
                  <Option value={2}>会员</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <Icon type="down" />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
      cardList,
      allTagList,
      match,
    } = this.props;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 8 },
    };
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="关键词" {...formItemLayout}>
              {getFieldDecorator('KeyWord')(<Input placeholder="请输入" className="xkd-width-per-100"/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="客户身份" {...formItemLayout}>
              {getFieldDecorator('MemberType')(
                <Select placeholder="请选择" className="xkd-width-per-100">
                  <Option value={0}>全部</Option>
                  <Option value={1}>客户</Option>
                  <Option value={2}>会员</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="会员卡" {...formItemLayout}>
                {getFieldDecorator('CardIds',{
                    initialValue: [match.params.id/1],
                })(
                    <Select placeholder="请选择" className="xkd-width-per-100" mode="multiple">
                      {
                        cardList&&cardList.map((item)=>{
                           return <Option value={item.Id} key={item.Id}>{item.Name}</Option>
                        })
                      }
                    </Select>
                )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="最近消费时间" {...formItemLayout}>
              {getFieldDecorator('LastBuyDate')(
                <RangePicker className="xkd-width-per-100"   placeholder={['请输入日期', '请输入日期']}/>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="标签" {...formItemLayout}>
              {getFieldDecorator('TagIds')(
                <Select placeholder="请选择" className="xkd-width-per-100" mode="multiple">
                  {
                    allTagList&&allTagList.map((item)=>{
                        return <Option value={item.Id} key={item.Id}>{item.Name}</Option>
                    })
                  }
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="积分" {...formItemLayout}>
              {getFieldDecorator('Points')(
                <InputNumberRange />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="成为客户时间" {...formItemLayout}>
              {getFieldDecorator('CreateDate')(
                <RangePicker className="xkd-width-per-100"  placeholder={['请输入日期', '请输入日期']} />
              )}
            </FormItem>
          </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <div style={{ float: 'right', marginBottom: 24 }}>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
            {/* <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
              收起 <Icon type="up" />
            </a> */}
          </div>
        </div>
      </Form>
    );
  }

  renderForm() {
    //const { expandForm } = this.state;
    // return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
    return this.renderAdvancedForm();
  }

  onSelectChange = (selectedRowKeys) => {
    //console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  }

  handleUpdateModalVisible = () => {
    window.open(`/#/${window.storeId}/customer/detail`);
};

  render() {
    const {
      loading,
    //  customerList,
      customerListInfo,
      oemInfo,
    } = this.props;
    const {  modalVisible, selectedRowKeys,paginationProps,contentType,cardLoading } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
      contentType,
    };
    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
    };
    const columns = [
        {
          title: '客户信息',
          dataIndex: 'name',
          width:200,
          render: (text,record ) => (
              <div className={styles.customerInfo}>
                <List.Item>
                    <List.Item.Meta
                        avatar={<Avatar src={
                           record.HeadImgUrl +'?x-oss-process=style/240'
                        }  size={48} shape="square"/>}
                        title={
                          <div>
                            <div className={`xkd-text-ellipsis ${styles.customerName}`}  title={record.NickName}>{record.NickName}</div>
                            <div className={`xkd-text-ellipsis xkd-font13 ${styles.customerName}`}  title={record.Remark}>{record.Remark}</div>
                          </div>
                        }
                    />
                </List.Item>
                <div className={styles.tagBox}>
                    <Tag  color={record.CustomerType==='客户'?'geekblue':''} className={record.CustomerType==='会员'?styles.customerTag:''}>{record.CustomerType}</Tag>
                    <Tag  >{record.SystemTagType}</Tag>
                    {record.Tags&&record.Tags.map((tag,index) => {
                        if(tag.TagType==1){
                          return (
                                <Popconfirm placement="topRight" title={'确定删除该标签吗？'} onConfirm={()=>this.deleteTag(record.Id,tag.Id,index)} okText="确定" cancelText="取消">
                                  <Tag  key={tag.Id}><Icon type="close" /></Tag>
                                </Popconfirm>
                                )
                        }else{
                          return <Tag  key={tag.Id}>{tag.Name}</Tag>
                        }

                    })}
                </div>
              </div>
          )
        },
        {
          title: '手机号码',
          dataIndex: 'Telephone',
          render: val => <span>{val || '-'}</span>,
        },
        {
          title: '最近消费时间',
          dataIndex: 'LastBuyTime',
          render: val => <span>{val || '-'}</span>,
          // mark to display a total number
         // needTotal: true,
        },
        {
          title: '积分',
          dataIndex: 'TotalPoints',
          align: 'right',
          sorter:true,
          render: val => <span>{val}</span>,
        },
        {
            title: '消费金额（元）',
            dataIndex: 'TotalFee',
            align: 'right',
            sorter:true,
            render: val => <span>{val}</span>,
        },
        {
          title: '消费次数',
          dataIndex: 'TotalFeeNum',
          align: 'right',
          sorter: true,
          render: val => <span>{val}</span>,
        },
        {
            title: '客单价（元）',
            dataIndex: 'SingleFee',
            align: 'right',
            sorter: true,
            render: val => <span>{val}</span>,
        },
        {
          title: '操作',
          align: 'right',
          render: (text, record) => (
            <Fragment>
              <a onClick={() => this.handleUpdateModalVisible(true, record)}>详情</a>
            </Fragment>
          ),
        },
      ];
    return (
      <Fragment >
        <Card bordered={false} loading={cardLoading}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Button onClick={() => this.handleAdd(1)}>打标签</Button>
              <Button onClick={() => this.handleAdd(2)}>修改积分</Button>
              <Button onClick={() => this.handleAdd(3)}>发会员卡</Button>
            </div>
            <Table
              loading={loading}
              rowKey={record => record.Id}
              dataSource={customerListInfo.customerList}
              columns={columns}
              rowSelection={rowSelection}
              onChange={this.handleStandardTableChange}
              pagination={{...paginationProps,total:customerListInfo.total,current:customerListInfo.pageIndex,pageSize:customerListInfo.pageSize}}
            />
          </div>
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible} />
      </Fragment>
    );
  }
}

export default TableList;
